package cn.net.zyx.controller;

import cn.net.zyx.domain.Video;
import cn.net.zyx.domain.VideoOrder;
import cn.net.zyx.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description: OrderController <br>
 * date: 2021/5/8 16:23 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("api/v1/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private VideoService videoService;

    @RequestMapping("find_by_id")
    public Object findById(int videoId){
        // Video video = restTemplate.getForObject("http://localhost:9003/api/v1/video/find_by_id?videoId=" + videoId, Video.class);

//        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-video-service");

        //ServiceInstance serviceInstance = instances.get(0);
//        Video video = restTemplate.getForObject("http://cloud-video-service/api/v1/video/find_by_id?videoId=" + videoId, Video.class);

        Video video = videoService.findById(videoId);

        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setVideoId(video.getId());
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setCreateTime(new Date());
        videoOrder.setServerInfo(video.getServerInfo());

        return videoOrder;
    }

    @RequestMapping("save")
    public Object save(@RequestBody Video video){

        Integer num = videoService.save(video);
        HashMap<Object, Object> hashMap = new HashMap<>(2);
        hashMap.put("num",num);
        return hashMap;
    }

    // 用数字递增去模拟有规律的抛异常 失败
    int toException = 0;

    /**
     * 测试feign调用 使用post方式传输对象
     * @return
     */
    @RequestMapping("list")
    public Object list(HttpServletRequest request){
        /*try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        toException++;
        if (toException%3 == 0) {
            throw new RuntimeException();
        }

        HashMap<String,String> map = new HashMap<>();
        map.put("title1","java");
        map.put("title2","C");
        map.put("title3","C#");
        map.put("title4","C++");
        map.put("title5","Python");
        map.put("title6","Golang");

        map.put("port",request.getServerPort()+"");

        return map;
    }

}
